<?php

namespace App\V3\V3_2_7\Services;

use App\Services\CommonService;
use App\V3\V3_2_7\Models\LocationAnimalModel;
use App\V3\V3_2_7\Models\LocationLogModel;
use App\V3\V3_2_7\Models\OutAnimalTagModel;
use App\V3\V3_2_7\Models\ShelfLocationTagModel;
use App\V3\V3_2_7\Models\StorageManageModel;
use App\V3\V3_2_7\Models\StorageShelfLocationModel;
use Illuminate\Http\JsonResponse;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

class LocationLogService
{
    /**
     *日志列表
     * Author: zlf
     * Created at 2024/9/9 9:39
     * @param $data
     * @return JsonResponse|null
     * @throws \Random\RandomException
     */
    public static function logList($data): ?JsonResponse
    {
        $locaInfo = [];
        if (!empty($data['req_type'])) {
            $logInfo = LocationLogModel::query()->where([
                'in_out_type' => 3,
                'id' => $data['id'],
                'main_id' => $data['main_id'],
            ])->first();

            if (!empty($logInfo)) {
                $locaInfo['id'] = $logInfo['location_id'];
                $locaInfo['log_no'] = $logInfo['log_no'];

            }
        } else {
            $locaInfo = StorageShelfLocationModel::query()
                ->where([
                    'status' => 1,
                    'id' => $data['id'],
                    'main_id' => $data['main_id']
                ])->first();
        }

        if (!empty($locaInfo)) {
            $condition = [
                'delete_flag' => 0,
                'location_id' => $locaInfo['id'],
                'log_no' => $locaInfo['log_no'],
                'type' => $data['req_type'] ?? 0
            ];

            $list = LocationLogModel::query()
                ->where($condition)
                ->orderBy('created_at', 'desc')
                ->paginate($data['pageSize'], ['*'], '', $data['currentPage'])->toArray();
            if (!empty($list['data'])) {
                foreach ($list['data'] as &$val) {
                    $val['tag_id'] = "";
                    if (!empty($val['conent4'])) {
                        if (is_numeric((int)$val['conent4'])) {
                            $val['tag_id'] = (int)$val['conent4'];
                            $val['conent4'] = ShelfLocationTagModel::query()
                                ->where([
                                    'id' => $val['conent4']
                                ])->value('tag_name') ?? $val['conent4'];

                        }
                    }
                    $val['in_price'] = 0.00;
                    $val['sell_price'] = 0.00;
                    $val['animal_img'] = '';
                    $animalInfo = LocationAnimalModel::query()->where([
                        'location_id' => $val['location_id'],
                        'id' => $val['animal_id'],
                        'delete_flag' => 0
                    ])->first();
                    if (!empty($animalInfo)) {
                        $val['in_price'] = $animalInfo['in_price'];
                        $val['sell_price'] = $animalInfo['sell_price'];
                        $val['animal_img'] = $animalInfo['animal_img'];
                    }
                    $val['out_tag_content'] = '';
                    if (!empty($val['out_tag_id'])) {
                        $val['out_tag_content'] = OutAnimalTagModel::query()
                            ->where('id', $val['out_tag_id'])
                            ->value('tag_content') ?? '';
                    }
                }
            }
            return success($list);
        } else {
            return fail('', '无盒子信息');
        }
    }

    /**
     *日志情况
     * Author: zlf
     * Created at 2024/9/9 9:39
     * @param $data
     * @return JsonResponse|null
     * @throws \Random\RandomException
     */
    public static function logInfo($data): ?JsonResponse
    {
        $info = LocationLogModel::query()->where([
            'delete_flag' => 0,
            'id' => $data['id'],
            'main_id' => $data['main_id']
        ])->first();
        if (!empty($info['conent4'])) {
            $info['tag_id'] = "";
            if (in_array((int)$info['conent4'], [4, 5, 6, 7, 10, 11, 12, 13])) {
                $info['tag_id'] = $info['conent4'];
                $info['conent4'] = ShelfLocationTagModel::query()->where([
                    'id' => $info['conent4']
                ])->value('tag_name');
            }
        }
        return success($info);
    }

    public static function create($data, $time): ?JsonResponse
    {
        DB::beginTransaction();
        try {
            $logData = [];
            if (!empty($data['log_data'])) {
                $logData = json_decode($data['log_data'], true, 512, JSON_THROW_ON_ERROR);
            } else {
                throw new \RuntimeException('日志数据，不能为空！');
            }
            if (!empty($data['location_ids'])) {
                $idArr = explode(',', $data['location_ids']);
                foreach ($idArr as $val) {
                    $locaInfo = StorageShelfLocationModel::query()
                        ->where([
                            'status' => 1,
                            'id' => $val,
                            'main_id' => $data['main_id']
                        ])->first();

                    if (LocationLogModel::query()->where([
                        'location_id' => $locaInfo['id'],
                        'main_id' => $data['main_id'],
                        'log_no' => $locaInfo['log_no'],
                        'type' => 1
                    ])->exists()) {
                        throw new \RuntimeException('盒子：' . $locaInfo['location_name'] . '日志已归档，不能创建!');
                    }
                    foreach ($logData as &$lVal) {
                        $lVal['log_no'] = $locaInfo['log_no'];
                        $lVal['location_id'] = $locaInfo['id'];
                        $lVal['main_id'] = $data['main_id'];
                        $lVal['user_id'] = $data['user_id'];
                    }
                    $bool = LocationLogModel::query()->insert($logData);
                    if ($bool) {
                        $info = LocationLogModel::query()->where([
                            'main_id' => $data['main_id'],
                            'delete_flag' => 0,
                            'location_id' => $locaInfo['id'],
                            'log_no' => $locaInfo['log_no'],
                            'type' => 0
                        ])->orderBy('created_at', 'desc')->first();
                        if (!empty($info['conent4'])) {
                            if (in_array((int)$info['conent4'], [11, 12, 13, 6], true)) {
                                StorageShelfLocationModel::query()->where([
                                    'id' => $info['location_id']
                                ])->update(['tag_id' => 6]);
                            }
                            if ((in_array((int)$info['conent4'], [4, 5, 7, 10], true))) {
                                StorageShelfLocationModel::query()
                                    ->where([
                                        'id' => $info['location_id']
                                    ])->update(['tag_id' => $info['conent4']]);
                            }
                        }
                    } else
                        throw new \RuntimeException('盒子：' . $locaInfo['location_name'] . ' 日志,添加失败！');
                }
                CommonService::operateResult($data['user_id'], $time, $logData, '添加成功');
                DB::commit();
                return success();
            } else {
                throw new \Exception('请选择盒子！');
            }
        } catch (\Exception $e) {
            DB::rollBack();
            Log::debug('添加盒子日志异常' . var_export($e->getMessage(), true));
            return fail('', $e->getMessage());
        }
    }

    public static function upd($data, $time): ?JsonResponse
    {
        $bool = false;
        DB::beginTransaction();
        try {
            $logInfo = LocationLogModel::query()->where([
                'delete_flag' => 0,
                'id' => $data['id'],
                'main_id' => $data['main_id']])->first();
            if (!empty($logInfo)) {
                if (!empty($logInfo['type'])) {
                    throw new \RuntimeException('日志已归档，不能修改!');
                }
                $bool = LocationLogModel::query()->where('id', $data['id'])->update($data);
            } else {
                throw new \RuntimeException('没有找到，盒子日志信息!');
            }
            if ($bool) {
                $info = LocationLogModel::query()->where([
                    'main_id' => $data['main_id'],
                    'delete_flag' => 0,
                    'location_id' => $data['id'],
                    'log_no' => $logInfo['log_no']
                ])->orderBy('created_at', 'desc')->first();
                if (!empty($info['conent4'])) {
                    if (in_array((int)$info['conent4'], [11, 12, 13, 6], true)) {
                        StorageShelfLocationModel::query()->where([
                            'id' => $info['location_id']
                        ])->update(['tag_id' => 6]);
                    }
                    if ((in_array((int)$info['conent4'], [4, 5, 7, 10], true))) {
                        StorageShelfLocationModel::query()
                            ->where([
                                'id' => $info['location_id']
                            ])->update(['tag_id' => $info['conent4']]);
                    }
                }
                CommonService::operateResult($data['user_id'], $time, $data, '修改成功');
                DB::commit();
                return success();
            } else
                throw new \RuntimeException('修改失败');
        } catch (\Exception $e) {
            DB::rollBack();
            Log::debug('修改盒子日志异常：' . var_export($e->getMessage(), true));
            return fail('', $e->getMessage());
        }
    }

    public static function del($data, $time): ?JsonResponse
    {
        $bool = false;
        DB::beginTransaction();
        try {
            $logInfo = LocationLogModel::query()->where([
                'delete_flag' => 0,
                'id' => $data['id'],
                'main_id' => $data['main_id']])->first();
            if (!empty($logInfo)) {
                if (!empty($logInfo['type'])) {
                    throw new \RuntimeException('日志已归档，不能删除!');
                }
                $logInfo->delete_flag = 1;
                $bool = $logInfo->save();
            } else {
                throw new \RuntimeException('没有找到，盒子日志信息!');
            }
            if ($bool) {
                CommonService::operateResult($data['user_id'], $time, $data, '删除成功');
                DB::commit();
                return success();
            } else
                throw new \RuntimeException('删除失败');
        } catch (\Exception $e) {
            DB::rollBack();
            Log::debug('删除盒子日志异常：' . var_export($e->getMessage(), true));
            return fail('', $e->getMessage());
        }
    }

    public static function getStorageAnimalList($data, $condition = [], $flag = 0)
    {
        $query = StorageShelfLocationModel::query()
            ->select(
                'd.id',
                'a.id as location_id',
                'shelf_id',
                'a.storage_id',
                'shelf_name',
                'location_name',
                'animal_name',
                'gene',
                'gram_weight',
                'sex',
                'c.num',
                'd.log_no',
                'd.type_time',
                'e.storage_name',
                'd.remark',
                'd.out_tag_id',
                'c.in_price',
                'c.sell_price',
                'f.tag_content'
            )->from('storage_shelf_location as a')
            ->leftJoin('storage_shelf as b', 'b.id', '=', 'a.shelf_id')
            ->leftJoin('location_animal as c', 'c.location_id', '=', 'a.id')
            ->leftJoin('location_log as d', 'd.animal_id', '=', 'c.id')
            ->leftJoin('storage as e', 'e.id', '=', 'a.storage_id')
            ->leftJoin('out_animal_tag as f', 'f.id', '=', 'd.out_tag_id')
            ->where([
                'd.type' => 1,
                'a.status' => 1,
                'b.status' => 1,
                'c.delete_flag' => 0,
                'd.delete_flag' => 0,
                'e.delete_flag' => 0,
                'd.in_out_type' => !empty($data['type']) ? 1 : 3,
            ]);
        if (!empty($condition)) {
            $query->where($condition);
        } else {
            $query->where([
                'd.main_id' => $data['main_id']
            ]);
        }
        $query->orderBy('d.created_at', 'desc');
        if ($flag === 1) {
            return $query->get();
        } else {
            return $query->paginate($data['pageSize'], ['*'], '', $data['currentPage'])->toArray();
        }
    }
}
